<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    
</body>
</html>
<script>

let data = [
    {
        id: "1",
        name: "1",
        children: [
            {
                id: "1-1",
                name: "1.1",
                pid: 1,
                children: [
                    {
                        id: "1-1-1",
                        name: "1.1.1",
                        pid: "1-1",
                        children: [
                            {
                                id: "1-1-1-1",
                                name: "1.1.1.1",
                                pid: "1-1-1"
                            }
                        ]
                    }
                ]
            }
        ]
    },
    {
        id: "2",
        name: "2",
        children: [
            {
                id: "2-1",
                name: "2.1",
                pid: "2",
                children: [
                    {
                        id: "2-1-1",
                        name: "2.1.1",
                        pid: "2-1"
                    }
                ]
            }
        ]
    }
]

//现在要在上面的数据中找到下面这个对象
let targetData = {
    id: "1-1-1-1",
    name: "1.1.1.1",
    pid: "1-1-1"
};

let findData;
//整理数据
function changeData(arr, targetData){
    arr.map((item, key) => {
        //查找当前层级中, 哪条数据的id和targetData的pid相同
        let findIndex = arr.findIndex((val) => val.id == targetData.pid);
        //如果没有相同的, 并且当前的这个 item 有子数据那么就到它的子数据中去找
        if(findIndex == -1 && item.children){
            changeData(item.children, targetData);
            return;
        }
        //如果找到了, 那么它就一定有 children 数组。然后直接从它的 children 数组中去找到 targetData 就好了
        if(findIndex != -1){
            let seekIndex = item.children.findIndex((val, index) => val.id == targetData.id);
            //将找到的数据赋值给 findData
            findData = item.children[seekIndex];
        }
    })
}
changeData(data, targetData);

console.log(findData);


</script>